/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2022-05-03 12:50:21
 * @LastEditors: machinist_wq
 * @LastEditTime: 2022-09-02 22:18:42
 * @Description: 弹窗验证码
 * 人生无常！大肠包小肠......
 */
import { useEffect, useMemo, useState } from "react";
import { Modal, Button, Alert, message } from "antd";
import { CloseCircleOutlined, SyncOutlined } from "@ant-design/icons";
import { generateCaptcha, verifyAnswer } from "@/service/login";
import styles from "./index.less";

const MachineVerify = props => {
  const [captchaData, setCaptchaData] = useState(null);
  const [anchorData, setAnchorData] = useState([]);
  const [isSuccess, setIsSuccess] = useState(0);

  useEffect(() => {
    getGenerateCaptcha();
  }, []);

  const getRotateText = useMemo(
    () =>
      (data => {
        return data.split(",").map((item, index) => {
          let rotate = Math.floor(Math.random() * 181) - 90;
          return (
            <span
              style={{
                marginRight: 10,
                fontSize: 24,
                transform: `rotate(${rotate}deg)`,
              }}
              key={index}>
              {item}
            </span>
          );
        });
      })(captchaData?.keywords?.words || ""),
    [captchaData]
  );

  const getGenerateCaptcha = () => {
    if (anchorData.length) setAnchorData([]);
    generateCaptcha({ type: "captcha_point" }).then(resp => {
      if (resp.status === 1) {
        setCaptchaData(resp.data);
      } else {
        message.error(resp.message);
      }
    });
  };

  const handleImgClick = event => {
    const {
      nativeEvent: { offsetX, offsetY },
    } = event;
    if (anchorData.length >= 7) {
      setAnchorData([]);
    } else {
      setAnchorData([...anchorData, { offsetX, offsetY }]);
    }
  };

  const handleSignClick = count => {
    let _anchorData = anchorData.slice(0, count);
    setAnchorData([..._anchorData]);
  };

  const confirmVerifyAnswer = () => {
    verifyAnswer({
      captchaId: captchaData.captchaId,
      captchaAnswer: anchorData
        .map(item => [item.offsetX, item.offsetY])
        .flat()
        .toString(),
    }).then(resp => {
      if (resp.status === 1) {
        setIsSuccess(2);
        setTimeout(() => {
          setAnchorData([]);
          setIsSuccess(0);
          //将验证通过的captchaId带回到业务组件中
          props.confirmSign(captchaData.captchaId);
        }, 1000);
      } else {
        setIsSuccess(1);
        setTimeout(() => {
          setAnchorData([]);
          getGenerateCaptcha();
          setIsSuccess(0);
        }, 1000);
      }
    });
  };

  return (
    <Modal
      closable={false}
      header={null}
      footer={null}
      width={376}
      className={"verification_code"}
      bodyStyle={{ padding: "4px 8px" }}
      onCancel={() => props.handleCancel()}
      visible={true}>
      {captchaData ? (
        <div className={"img_number"}>
          <span style={{ display: "flex", alignItems: "start" }}>
            请在下图<span style={{ color: "#1c75e4" }}>依次</span>点击：
            {getRotateText}
          </span>
          <div className={"img_box"}>
            {anchorData.map((item, index) => {
              return (
                <div
                  key={index}
                  style={{
                    top: item.offsetY - 12,
                    left: item.offsetX - 12,
                  }}
                  className={"sign"}
                  onClick={() => handleSignClick(index)}>
                  <div className={"inner_box"}>{index + 1}</div>
                </div>
              );
            })}
            <img
              onClick={handleImgClick}
              src={`/api/base/captcha/getCaptchaImage?captchaId=${captchaData.captchaId}&imageName=${captchaData.imageUrls.bg}`}
              alt=""
            />

            <Alert
              className={"alert"}
              style={{ bottom: isSuccess === 0 ? -40 : 0 }}
              message={`验证${isSuccess === 1 ? "失败" : "成功"}`}
              type={isSuccess === 1 ? "error" : "success"}
              showIcon
            />
          </div>

          <div className={"btn_group"}>
            <Button
              onClick={() => props.handleCancel()}
              size={"large"}
              type="text"
              shape="circle"
              icon={<CloseCircleOutlined />}></Button>
            <Button
              onClick={() => getGenerateCaptcha()}
              size={"large"}
              type="text"
              shape="circle"
              icon={<SyncOutlined />}></Button>
            <Button
              onClick={() => confirmVerifyAnswer()}
              className={"confirm_btn"}
              type="primary">
              确定
            </Button>
          </div>
        </div>
      ) : null}
    </Modal>
  );
};

export default MachineVerify;
